package com.haople.sso.web.service.impl;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.haople.sso.core.authentication.TicketAuthorization;
import com.haople.sso.core.util.TicketUtil;
import com.haople.sso.core.vo.Ticket;
import com.haople.sso.web.service.UserTicketService;

@Service
public class UserTicketServiceImpl implements UserTicketService {

	private static final Logger logger=Logger.getLogger(UserTicketServiceImpl.class);
	
	@Value("${ticket_prefix}")
	private String ticketPrefix;
	
	@Autowired
	private TicketAuthorization ticketAuthorization;
	
	/**
	 * 保存票据
	 * @param userName
	 * @param password
	 * @return 返回保存的票据
	 * @throws Exception 
	 */
	public String saveTicket(String userId) throws Exception {
		if(StringUtils.isEmpty(ticketPrefix)){
			logger.warn("ticketPrefix is empty");
		}
		String t=ticketPrefix+TicketUtil.getTicket();
		Ticket ticket=new Ticket();
		ticket.setCreateDate(new Date());
		ticket.setTicket(t);
		ticket.setUserId(userId);
		ticketAuthorization.save(ticket);
		logger.info("userId-->"+userId+"---保存票据-->"+t);
		return t;
	}

	/**
	 * 根据用户可以获取
	 * @param userKey
	 * @return
	 * @throws Exception
	 */
	public Ticket getTicket(String userKey) throws Exception {
		
		return ticketAuthorization.get(userKey);
	}

}
